
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "maincontent.h"
#include "symboltabledlg.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    model = new MainContent(this);

    symtbldlg = new SymbolTableDlg;

    symtblready = 0;

    connect(ui->btnLoad, SIGNAL(clicked()), this, SLOT(LoadImgFile()));
    connect(ui->btnSymTbl, SIGNAL(clicked()), this, SLOT(ShowSymTbl()));
    connect(ui->textSymbol, SIGNAL(textChanged()), this, SLOT(ShowSymAddr()));
    connect(this, SIGNAL(SetProgressBar(int)), ui->prbrSymbol, SLOT(setValue(int)));
    connect(symtbldlg, SIGNAL(SendSymName(QString)), this, SLOT(GetSymName(QString)));
}

MainWindow::~MainWindow()
{
    delete symtbldlg;
    delete model;
    delete ui;
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MainWindow::LoadImgFile()
{
    QString fileName = QFileDialog::getOpenFileName(this,
        tr("Load Image File"), "",
        tr("CCS C6000 COFF(*.out);;All Files (*)"));

    if (fileName.isEmpty())
        return;
    else {

        QFile file(fileName);

        if (!file.open(QIODevice::ReadOnly)) {
            QMessageBox::information(this, tr("Unable to open file"),
                file.errorString());
            return;
        }

        ui->textLoadImg->setText(fileName);

        model->ParseFile(&file);

        file.close();

        symtblready = 1;
    }
}

void MainWindow::ShowSymAddr()
{
    QString SymbolName = ui->textSymbol->toPlainText();
    quint32 SymbolAddr = 0;

    if(model->QuerySymbol(SymbolName, SymbolAddr)
      || model->QuerySymbol(QString("_")+SymbolName, SymbolAddr)
       )
    {
        QString SymbolData(tr("Symbol address: "));
        SymbolData += QString("%1").arg(SymbolAddr, 8, 16, QLatin1Char('0'));
        SymbolData += "\r\n";

        ui->textSymData->setText(SymbolData);
    }
    else
    {
        ui->textSymData->setText(QString("Invalid Symbol!\r\n"));
    }
}

void MainWindow::ShowSymTbl()
{
    if(symtblready)
    {
        QString s;
        quint32 v;
        quint32 percent =0;
        quint32 ctr =0;

        symtbldlg->ClearSymbolTable();
        model->ResetIter();
        while(model->IterSymbol(s,v))
        {
            symtbldlg->LoadSymbolTable(s,v);

            ctr ++;
            percent = ctr * 100 / model->SymbolCnt();
            emit SetProgressBar(percent);
        }

        symtblready = 0;
    }

    this->symtbldlg->show();
}

void MainWindow::GetSymName(QString name)
{
    this->ui->textSymbol->setText(name);
}
